<template>
  <div>
    <el-row :gutter="10" type="flex" justify="start">
      <span class="label">企业管理:</span>
      <el-input
        v-model="pageParams.name"
        placeholder="请输入楼宇名称"
        class="input"
        size="small"
        @keyup.enter.native="onSearch"
      />
      <el-button type="primary" size="small" @click="onSearch">查询</el-button>
    </el-row>
    <el-divider />
    <el-button
      type="primary"
      size="small"
      style="margin-bottom: 20px"
      @click="
        $router.push({ path: '/park/enterprise/add', query: { mode: 'add' } })
      "
    >添加企业</el-button>
    <el-table
      v-loading="loading"
      :data="list"
      style="width: 100%"
      @expand-change="handleRowClick"
    >
      <el-table-column
        header-align="center"
        align="center"
        type="expand"
      >
        <template #default="{row}">
          <el-table
            ref="childTable"
            :data="row.rentDetail"
            style="width: 100%"
            :header-cell-style="{ backgroundColor: '#f4f6f8'}"
          >
            <template slot="empty">
              <img src="../../../assets/empty.svg" alt style="margin: 120px auto 8px auto; height: 50; width: 78px; display: block">
              <p style="line-height: 22px; font-size: 14px; margin-bottom: 60px">暂无数据</p>
            </template>
            <el-table-column
              label="租赁楼宇"
              width="width"
              prop="buildingName"
            />
            <el-table-column
              label="租赁起止时间"
              width="width"
            >
              <template #default="{row}">
                {{ row.startTime+' 至 '+row.endTime }}
              </template>
            </el-table-column>
            <el-table-column
              label="合同状态"
              width="width"
            >
              <template #default="{row}">
                <el-tag v-if="row.status===0" type="primary" plain>待生效</el-tag>
                <el-tag v-else-if="row.status===1" type="success" plain>生效中</el-tag>
                <el-tag v-else-if="row.status===2" type="warning" plain>已到期</el-tag>
                <el-tag v-else-if="row.status===3" type="info" plain>退租</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="width"
            >
              <template #default="{row}">
                <el-button type="text" :disabled="!row.renewFlag" @click="onRentKeep(row)">续租</el-button>
                <el-button type="text" :disabled="!row.exitFlag" @click="onRentOut(row)">退租 </el-button>
                <el-button type="text" :disabled="row.status!==3" @click="onRentDel(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="序号" width="width" type="index" :index="index" />
      <el-table-column
        header-align="center"
        align="center"
        prop="name"
        label="企业名称"
      />
      <el-table-column
        header-align="center"
        align="center"
        prop="contact"
        label="联系人"
      />
      <el-table-column
        header-align="center"
        align="center"
        prop="contactNumber"
        label="联系电话"
      />
      <el-table-column prop="prop" label="操作" width="width">
        <template #default="{ row }">
          <el-button type="text" @click="addRent(row.id)">添加合同</el-button>
          <el-button
            type="text"
            @click="$router.push(`/park/enterprise/detail/${row.id}`)"
          >查看</el-button>
          <el-button
            type="text"
            :disabled="!!row.demoFlag"
            @click="
              $router.push({
                path: '/park/enterprise/add',
                query: { mode: 'edit', id: row.id },
              })
            "
          >编辑</el-button>
          <el-button
            type="text"
            :disabled="!!row.demoFlag"
            @click="onDel(row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <my-pagination
      :total="total"
      @change="
        (val) => {
          pageParams = Object.assign(pageParams, val);
          getList();
        }
      "
    />
    <el-dialog :title="rentInfo.type?'续租合同':'添加合同'" :visible.sync="visible" width="width">
      <el-form ref="rentRef" :model="rentInfo" :rules="rules" label-position="top">
        <el-form-item label="租赁楼宇" prop="buildingId">
          <el-select
            v-if="!rentInfo.type"
            v-model="rentInfo.buildingId"
            placeholder="请选择租赁的楼宇"
            style="width: 100%"
          >
            <el-option
              v-for="item in rentBuildings"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-input v-else :placeholder="rentBuildName" disabled />
        </el-form-item>
        <el-form-item label="租赁起止日期" prop="startTime">
          <el-date-picker
            v-model="rentInfo.startTime"
            style="width: 100%"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            :clearable="false"
          />
        </el-form-item>
        <el-form-item label="租赁合同" prop="contractUrl">
          <upload
            ref="uploadRef"
            :file-array="fileArray"
            :file-size="5"
            type="contract"
            tip-content="支持扩展名：.doc .docx .pdf, 文件大小不得超过5M"
            @onSuccess="handlerSuccess"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getEpListAPI, delEpAPI, addRentAPI, getRentAPI, updateRentAPI, delRentAPI } from '@/api/enterprise'
import { onSecondConfirm } from '@/utils'
import MyPagination from '@/components/my-pagination'
import Upload from '@/views/Park/Enterprise/components/upload.vue'
import { getRentBuildAPI } from '@/api/building'

export default {
  components: {
    MyPagination,
    Upload
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 3600 * 1000 * 24
        }
      },
      fileArray: ['doc', 'docx', 'pdf'],
      visible: false,
      list: [],
      total: 0,
      loading: false,
      pageParams: {
        name: '',
        page: '1',
        pageSize: '10'
      },
      rentInfo: {
        buildingId: null,
        startTime: '',
        endTime: '',
        contractUrl: '',
        contractId: 0,
        type: 0, // 操作类型，添加合同0，续签合同1
        enterpriseId: 0
      },
      rentBuildings: [],
      rules: {
        buildingId: [{ required: true, message: ' ', trigger: 'blur' }],
        startTime: [{ required: true, message: ' ', trigger: 'blur' }],
        contractUrl: [
          { required: true, message: '请上传租赁合同', trigger: 'change' }
        ]
      },
      rentBuildName: ''
    }
  },
  computed: {
    index() {
      return this.pageParams.page > 1
        ? (this.pageParams.page - 1) * this.pageParams.pageSize + 1
        : 1
    }
  },
  watch: {
    visible(val) {
      if (val === false) {
        this.$refs.uploadRef.clear()
        this.$refs.rentRef.resetFields()
      }
    },
    'rentInfo.contractUrl'(newVal, oldVal) {
      if (newVal !== oldVal && newVal !== '') {
        this.$refs.rentRef.clearValidate(['contractUrl'])
      }
    },
    rentDetail(val) {
      this.rentDetail = val
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async onRentKeep(row) {
      this.rentInfo.type = 1
      // 获取可租赁的楼宇
      this.rentBuildings = await getRentBuildAPI()
      this.rentInfo.buildingId = row.buildingId
      // 回填时间选择器的开始日期
      const inputDate = new Date(row.endTime)
      inputDate.setDate(inputDate.getDate() + 1)
      this.rentInfo.startTime = [inputDate, new Date('')]

      this.pickerOptions = {
        disabledDate(time) {
          return time.getTime() < inputDate - 3600 * 1000 * 24
        }
      }

      this.rentInfo.enterpriseId = row.pid
      this.rentBuildName = row.buildingName
      // 修改title
      // 弹框显示
      this.visible = true
    },
    onRentDel(row) {
      onSecondConfirm({
        content: '是否确认删除当前合同?',
        handler: async() => {
          // 调接口
          await delRentAPI(row.id)
          // 提示用户
          this.$message.success('删除成功!')

          this.updateInlineTable(this.pid)
        }
      })
    },
    onRentOut(row) {
      onSecondConfirm({
        content: '退租不可撤回,是否确认退租当前楼宇?',
        handler: async() => {
          // 调接口
          await updateRentAPI(row.id)
          // 提示用户
          this.$message.success('操作成功!')
          // eslint-disable-next-line require-atomic-updates
          row.status = 3
          // eslint-disable-next-line require-atomic-updates
          row.exitFlag = 0
        }
      })
    },
    async handleRowClick(row, expandedRows) {
      // 根据row.id请求数据渲染 expandedRows展开行的数据
      if (expandedRows.length > 0) {
        this.uploadFlag = true
        this.pid = row.id
        const res = await getRentAPI(row.id)
        res.forEach((item, i) => { item.pid = row.id })
        this.list.forEach((item, i) => {
          if (item.id === row.id) {
            this.list[i].rentDetail = res
          }
        })
      } else {
        this.uploadFlag = false
      }
    },
    onSubmit() {
      this.$refs.rentRef.validate(async(isOk) => {
        if (isOk) {
          const [sTime, eTime] = this.rentInfo.startTime
          this.rentInfo.startTime = sTime
          this.rentInfo.endTime = eTime
          // 发请求
          await addRentAPI(this.rentInfo)
          // 刷新inlineTable的数据
          this.updateInlineTable(this.rentInfo.enterpriseId)
          // 提示用户
          this.$message.success('添加成功!')
          // 清空表单
          this.$refs.uploadRef.clear()
          // 关闭弹窗
          this.visible = false
        }
      })
    },
    async updateInlineTable(id) {
      const res = await getRentAPI(id)
      this.list.forEach((item, i) => {
        if (item.id === id) {
          this.list[i].rentDetail = res
        }
      })
      // 判断需不需要强制刷新
      this.uploadFlag && this.$forceUpdate()
    },
    handlerSuccess(res) {
      this.rentInfo.contractId = res.id
      this.rentInfo.contractUrl = res.url
    },
    async addRent(enterpriseId) {
      this.rentInfo.enterpriseId = enterpriseId
      // 获取可租赁的楼宇
      this.rentBuildings = await getRentBuildAPI()
      this.visible = true
    },
    onDel(id) {
      onSecondConfirm({ handler: async() => {
        await delEpAPI(id)
        this.$message.success('删除成功!')
        this.getList()
      } })
    },
    async onSearch() {
      await this.getList()
    },
    async getList() {
      this.loading = true
      const res = await getEpListAPI(this.pageParams)
      this.total = res.total
      // 添加展开行数据
      res.rows.forEach(i => {
        i.rentDetail = []
      })
      this.list = res.rows
      this.loading = false
    }
  }
}
</script>

<style lang="scss" scoped>
.label {
  padding-right: 10px;
  line-height: 32px;
  font-size: 14px;
}
.input {
  width: 250px !important;
  margin-right: 10px;
}
::v-deep .el-table__expanded-cell[class*=cell] {
    padding: 0px;
    padding-left: 30px;
    background-color: #f4f6f8;
}
::v-deep .el-table__expanded-cell:hover {
   background-color: #f4f6f8 !important;
}
.el-table__empty-text{
  display: block;
}
</style>
